import Vue from 'vue'
import Vuex from 'vuex'
import { createApi } from '../api'
import { formatDate } from '../utils'

Vue.use(Vuex)

export const createStore = () => {
  return new Vuex.Store({
    state: {
      taskList: []
    },
    actions: {
      fetchTaskList ({ commit }, payload) {
        let params = {
          page: 1,
          size: 10
        }
        if (payload) {
          params = {
            ...params,
            ...payload
          }
        }
        const { page, size } = params
        return createApi(`/task/list?page=${page}&size=${size}`, 'get')
          .then(res => {
            const { code, data } = res
            if (code === 0) {
              data.forEach(item => {
                item.time = formatDate(item.time)
                item.status = item.status ? item.status : '等待推送'
              })
              commit('updateTask', { data })
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    mutations: {
      updateTask (state, payload) {
        const { data } = payload
        state.taskList = data
      }
    },
    getters: {
      taskList: state => state.taskList
    }
  })
}
